package com.example.demo.utils;

import com.example.demo.listener.ConsoleEventSourceListener;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSources;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.stereotype.Component;

import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.cert.X509Certificate;
import java.util.Objects;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@Slf4j
public class DifyClient {
    private static final String API_BASE_URL = "https://api.dify.ai/v1";
    private final String apiKey;
    private final OkHttpClient httpClient;
    private final ObjectMapper objectMapper;

    public DifyClient(String apiKey) {
        this.apiKey = Objects.requireNonNull(apiKey, "API key must not be null");
        this.httpClient = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .sslSocketFactory(createSSLSocketFactory(), trustAllCerts[0])
                .hostnameVerifier((hostname, session) -> true)
                .retryOnConnectionFailure(true)
                .build();
        this.objectMapper = new ObjectMapper();
    }

    private static final X509TrustManager[] trustAllCerts = new X509TrustManager[]{
            new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType) {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType) {
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[]{};
                }
            }
    };

    private static SSLSocketFactory createSSLSocketFactory() {
        try {
            javax.net.ssl.SSLContext sslContext = javax.net.ssl.SSLContext.getInstance("TLSv1.2");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            return sslContext.getSocketFactory();
        } catch (Exception e) {
            throw new RuntimeException("Failed to create SSL socket factory", e);
        }
    }

    public ServerSentEvent<String> runWorkflow(String query)  throws Exception{
        // 参数验证
        String result="";
        if (query == null || query.trim().isEmpty()) {
            throw new IllegalArgumentException("查询内容不能为空");
        }

        String url = API_BASE_URL + "/workflows/run";

        ObjectNode requestBody = objectMapper.createObjectNode();
        ObjectNode inputs = objectMapper.createObjectNode();
        inputs.put("list", query);
        requestBody.set("inputs", inputs);
        requestBody.put("response_mode", "streaming");
        requestBody.put("user", "user");

        Request request = new Request.Builder()
                .url(url)
                .addHeader("Authorization", "Bearer " + apiKey)
                .addHeader("X-API-Version", "v1")
                .addHeader("Content-Type", "application/json")
                .post(RequestBody.create(
                        MediaType.parse("application/json"),
                        objectMapper.writeValueAsString(requestBody)))
                .build();
        EventSource.Factory factory = EventSources.createFactory(httpClient);
        CountDownLatch countDownLatch = new CountDownLatch(1);
        EventSource eventSource = factory.newEventSource(request,new ConsoleEventSourceListener(countDownLatch));
        countDownLatch.await();
//        Response response = httpClient.newCall(request).execute();
//        System.out.println(response);
//        try (Response response = httpClient.newCall(request).execute()) {
//            if (!response.isSuccessful()) {
//                String errorBody = response.body() != null ? response.body().string() : "No error body";
//                JsonNode errorJson = null;
//                String errorMessage = errorBody;
//                try {
//                    errorJson = objectMapper.readTree(errorBody);
//                    if (errorJson.has("message")) {
//                        errorMessage = errorJson.get("message").asText();
//                    }
//                } catch (Exception e) {
//                    logger.warn("Failed to parse error response as JSON", e);
//                }
//
//                if (response.code() == 400 && errorBody.contains("app_unavailable")) {
//                    throw new IOException("应用配置无效或未启用，请检查Application ID是否正确，以及应用是否已在Dify平台启用");
//                }
//
//                throw new IOException(String.format("请求失败: %s, 状态码: %d, 错误信息: %s",
//                        response.request().url(), response.code(), errorMessage));
//            }
//
//            ResponseBody responseBody = Objects.requireNonNull(response.body());
//            try (BufferedReader reader = new BufferedReader(new InputStreamReader(responseBody.byteStream()))) {
//                String line;
//                StringBuilder fullResponse = new StringBuilder();
//                while ((line = reader.readLine()) != null) {
//                    if (!line.trim().isEmpty()) {
//                        // 处理流式响应中的data前缀
//                        if (line.startsWith("data: ")) {
//                            line = line.substring(6);
//                        }
//                        try {
//                            JsonNode jsonNode = objectMapper.readTree(line);
//                            if (jsonNode.has("data") && jsonNode.get("data").has("outputs")) {
//                                JsonNode outputs = jsonNode.get("data").get("outputs");
//                                if (outputs.has("result")) {
//                                    result = outputs.get("result").asText();
//                                    // 检查是否已包含相同内容
//                                    if (!fullResponse.toString().contains(result)) {
//                                        fullResponse.append(result);
////                                        System.out.print(result);
//                                        return result;
//                                    }
//                                }
//                            }
//                        } catch (JsonProcessingException e) {
//                            logger.warn("Failed to parse streaming response JSON: {}", line);
//                        }
//                    }
//                }
//                System.out.println(); // 添加换行
//            }
//        }
        return null;
    }
}